package com.lepu.app.main.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.app.utils.LoginUtil;
import com.app.utils.MyStoreUtil;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragment;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.UmengHelper;
import com.lepu.app.fun.health.activity.HealthWebActivity;
import com.lepu.app.fun.health.activity.MapActivity;
import com.lepu.app.fun.health.bean.BeanHealth;
import com.lepu.app.fun.my.adapter.AdapterMyArticle;
import com.lepu.app.fun.my.bean.BeanMyArticle;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.main.bean.BeanFocus;
import com.lepu.app.widget.FocusOneView;
import com.lepu.app.widget.FocusView;
import com.lepu.pasm.R;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainTabFragmentHealth extends BaseFragment implements AsyncRequest
        , SwipeRefreshLayout.OnRefreshListener {

    private static final String REQUEST_DATA = "request_data";

    private static final int MSG_DATA_SUCCESS = 10;
    private static final int MSG_DATA_FAIL = 11;

    private View mMainView = null;
    private boolean mInitDataSuccess = false;//是否加载完数据

    private SwipeRefreshLayout mRefreshLayout = null;
    private ListView mDataListView = null;
    ArrayList<BeanMyArticle> mDataArrayList;

    private FocusView mFocusViewTop = null; // 顶部轮播图
    private LinearLayout mFocusLayout = null;
    private View mHeaderTopView = null;

    public boolean mRefreshFlag = true;

    @SuppressLint("InflateParams")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mMainView = LayoutInflater.from(getActivity()).inflate(
                R.layout.main_tab_fragment_health, null,
                false);
        init();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        ViewGroup p = (ViewGroup) mMainView.getParent();
        if (p != null) {
            p.removeAllViewsInLayout();
        }
        return mMainView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mInitDataSuccess = false;
    }

    @Override
    public void onResume() {
        super.onResume();

        UmengHelper.OnPageStart(UmengEvent.page_health);

        if (mFocusViewTop != null) {
            mFocusViewTop.onResumeViewPager();
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        UmengHelper.OnPageEnd(UmengEvent.page_health);

        if (mFocusViewTop != null) {
            mFocusViewTop.onPauseViewPager();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
            if (!mInitDataSuccess || mRefreshFlag) {
                // 第一次进入页面获取数据
                mRefreshFlag = false;
                // 第一次进入页面获取数据
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        mRefreshLayout.setRefreshing(true);  //直接调用是没有用的
                    }
                }, 100);
                request();
            }
        }
    }

    /*
     * 初始化ui控件，不要初始化数据！！！！
     *
     * 初始化控件，需要用mMainView.findViewById
     * 不能使用findViewById，否则程序会闪退的
     */
    @SuppressWarnings("deprecation")
	private void init() {
        //5.0以下关闭硬件加速
        Utils.setLayerTypeOff(mMainView);

        mRefreshLayout = (SwipeRefreshLayout) mMainView.findViewById(R.id.swipeLayout);
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
                R.color.color_listview_refresh_2,
                R.color.color_listview_refresh_3,
                R.color.color_listview_refresh_4);
        mDataListView = (ListView) mMainView.findViewById(R.id.dataListView);

        //topView
        initTopHeader();
    }

    private void showHideNoDataLayout(boolean isShow) {
        LinearLayout noDataLayout = (LinearLayout) mMainView.findViewById(R.id.noDataLayout);
        if (noDataLayout != null) {
            if (isShow) {
                if (mDataArrayList == null || mDataArrayList.size() == 0) {
                    noDataLayout.setVisibility(View.VISIBLE);
                }else{
                    noDataLayout.setVisibility(View.GONE);
                }
            } else {
                noDataLayout.setVisibility(View.GONE);
            }
        }
    }

    private void initTopHeader() {

        mHeaderTopView = LayoutInflater.from(getActivity()).inflate(R.layout.main_tab_fragment_health_topview, null);
        mFocusLayout = (LinearLayout) mHeaderTopView.findViewById(R.id.healthFocusLayout);

        TextView yuanChengHuiZhenLayout = (TextView) mHeaderTopView.findViewById(R.id.yuanChengHuiZhenLayout);
        TextView marketLayout = (TextView) mHeaderTopView.findViewById(R.id.marketLayout);
        TextView peiZhenLayout = (TextView) mHeaderTopView.findViewById(R.id.peiZhenLayout);
        TextView zhuanZhenLayout = (TextView) mHeaderTopView.findViewById(R.id.zhuanZhenLayout);

        yuanChengHuiZhenLayout.setOnClickListener(mOnClickListener);
        marketLayout.setOnClickListener(mOnClickListener);
        peiZhenLayout.setOnClickListener(mOnClickListener);
        zhuanZhenLayout.setOnClickListener(mOnClickListener);
    }

    // 请求数据
    public void request() {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject params = new JSONObject();
        try {
            params.put("DeviceID", Setting.DEVICEID);
            params.put("ApplicationID", Setting.APPLICATIONID);

            params.put("UserID", LoginUtil.getUserId());
            params.put("LoginToken", LoginUtil.getLoginToken());

            params.put("ClientVersion", AppManager.getVersionCode(
                    getActivity(), getActivity().getPackageName()));
            params.put("BranchID", Setting.getBranchID(getActivity()));

        } catch (Exception e) {
        }
        map.put("ht", params);

        String url = Setting.getHealthDataUrl();

        ApiClient.http_post(url, map, null, this, REQUEST_DATA, true, false,
                true);
    }

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_DATA_SUCCESS:

                    if(getActivity() == null)
                    {
                        return;
                    }
                    mHandler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            mRefreshLayout.setRefreshing(false);
                        }
                    }, 100);

                    BeanHealth beanHealth = (BeanHealth) msg.obj;
                    if(beanHealth == null){
                        beanHealth = new BeanHealth();
                    }

                    // 轮播图
                    ArrayList<BeanFocus> focusList = beanHealth.BannerList;

                    if (focusList != null && focusList.size() > 0) {
                        mInitDataSuccess = true;
                        mFocusLayout.removeAllViews();

                        if(focusList.size() == 1)
                        {
                            FocusOneView focusOneViewArticle = new FocusOneView(getActivity(), focusList);
                            mFocusLayout.addView(focusOneViewArticle);
                        }else{
                            mFocusViewTop = new FocusView(getActivity(), focusList, FocusView.TYPE_DEFAULT, mRefreshLayout);
                            mFocusLayout.addView(mFocusViewTop);
                        }
                    }

                    mDataListView.removeHeaderView(mHeaderTopView);
                    mDataListView.addHeaderView(mHeaderTopView);

                    mDataArrayList = beanHealth.ArticleList;
                    AdapterMyArticle articleAdapter = new AdapterMyArticle(getActivity(), mDataArrayList, 40);
                    mDataListView.setAdapter(articleAdapter);

//                    if(mDataArrayList == null || mDataArrayList.size() == 0){
//                        showHideNoDataLayout(true);
//                    }else{
//                        showHideNoDataLayout(false);
//                    }

                    break;
                case MSG_DATA_FAIL:

                    if(getActivity() == null)
                    {
                        return;
                    }

                    mHandler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            mRefreshLayout.setRefreshing(false);
                        }
                    }, 100);
                    showHideNoDataLayout(true);
                    break;

                default:
                    break;
            }
        }

        ;
    };

    View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int rid = view.getId();
            switch (rid) {
                case R.id.yuanChengHuiZhenLayout:
                    //远程会诊
                    UmengHelper.CustomEvent(getActivity(), UmengEvent.event_fuwu_xunyiwenyao);

                	Intent intentMap = new Intent(getActivity(), MapActivity.class);
                	MainTabActivity.getInstance().startActivity(intentMap, true);
                    break;
                case R.id.marketLayout:
                    UmengHelper.CustomEvent(getActivity(), UmengEvent.event_jiankangshangcheng);

                    MyStoreUtil.getInstance().requestAllMarket(MainTabActivity.getInstance(), "");
                    break;
                case R.id.peiZhenLayout:

                    UmengHelper.CustomEvent(getActivity(), UmengEvent.event_fuwu_peizhenfuwu);

                    Intent intent = new Intent(getActivity(), HealthWebActivity.class);
                    intent.putExtra("url", Setting.getSuiXinZhenMainUrl());
                    intent.putExtra("title", getString(R.string.health_title_pei_zhen));
                    intent.putExtra("type", HealthWebActivity.TYPE_PEI_ZHEN);
                    MainTabActivity.getInstance().startActivity(intent, true);

                    break;
                case R.id.zhuanZhenLayout:

                    UmengHelper.CustomEvent(getActivity(), UmengEvent.event_fuwu_peizhenfuwu);
                    Intent intentZhuanZhen = new Intent(getActivity(), HealthWebActivity.class);
                    intentZhuanZhen.putExtra("url", Setting.getZhuanZhenMainUrl());
                    intentZhuanZhen.putExtra("title", getString(R.string.health_title_zhuan_zhen));
                    intentZhuanZhen.putExtra("type", HealthWebActivity.TYPE_ZHUAN_ZHEN);
                    MainTabActivity.getInstance().startActivity(intentZhuanZhen, true);

                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void RequestComplete(Object object, Object data)  {
        if (object.equals(REQUEST_DATA))
        {
            BeanHealth beanHealth = BeanHealth.parseJsonData((String) data);

            Message msg = mHandler.obtainMessage();
            msg.what = MSG_DATA_SUCCESS;
            msg.obj = beanHealth;
            mHandler.sendMessage(msg);
        }
    }

    @Override
    public void RequestError(Object object, int errorId, String errorMessage){
        if (object.equals(REQUEST_DATA)) {
            Message msg = mHandler.obtainMessage();
            msg.what = MSG_DATA_FAIL;
            mHandler.sendMessage(msg);
        }
    }

    @Override
    public void onRefresh() {
        request();
    }
}
